﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using Csla.Security;
using Csla.Serialization;
using log4net;

namespace Sireass.Bl.Security
{
	[Serializable]
	public class SireassIdentity : CslaIdentityBase<SireassIdentity>
	{
		// Create a logger for use in this class
		private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		public static readonly PropertyInfo<string> FullNameProperty = RegisterProperty<string>(c => c.FullName);
		public string FullName
		{
			get { return GetProperty(FullNameProperty); }
			private set { LoadProperty(FullNameProperty, value); }
		}
		public static readonly PropertyInfo<long> IdUsuarioProperty = RegisterProperty<long>(c => c.IdUsuario);
		public long IdUsuario
		{
			get { return GetProperty(IdUsuarioProperty); }
			private set { LoadProperty(IdUsuarioProperty, value); }
		}
		public static readonly PropertyInfo<long> IdPersonaProperty = RegisterProperty<long>(c => c.IdPersona);
		public long IdPersona
		{
			get { return GetProperty(IdPersonaProperty); }
			private set { LoadProperty(IdPersonaProperty, value); }
		}

		public static void GetIdentity(
		  string username, string password, EventHandler<DataPortalResult<SireassIdentity>> callback)
		{
			DataPortal.BeginFetch<SireassIdentity>(new UsernameCriteria(username, password), callback);
		}

		public static SireassIdentity GetIdentity(string username, string password)
		{
			return DataPortal.Fetch<SireassIdentity>(new UsernameCriteria(username, password));
		}

		internal static SireassIdentity GetIdentity(string username)
		{
			return DataPortal.Fetch<SireassIdentity>(username);
		}

		private void DataPortal_Fetch(UsernameCriteria criteria)
		{
			AuthenticationType = "Custom";
			IsAuthenticated = false;
			//var dal = new DataAccess.IdentityDal();
			//if (dal.VerifyUser(criteria.Username, criteria.Password))
			//    LoadUserData(criteria.Username, dal);
			using (var dalManager = Sireass.Dal.DalFactory.GetManager())
			{
				var dal = dalManager.GetProvider<Sireass.Dal.IUsuarioDal>();
				using (var data = new Csla.Data.SafeDataReader(dal.Fetch(criteria.Username, criteria.Password)))
				{
					if (data.Read() && data.GetBoolean("bHabilitado"))
					{
						IsAuthenticated = true;
						Name = data.GetString("cUsuario");
						IdUsuario = data.GetInt64("nIdUsuario");
						IdPersona = data.GetInt64("nId_Persona");
						FullName = data.GetString("cNombre") + " " + data.GetString("cApellido_Paterno");
						string apellidoMaterno = data.GetString("cApellido_Materno").Trim();
						if (apellidoMaterno != null && apellidoMaterno.Length > 0)
						{
							FullName += " " + apellidoMaterno;
						}
						if (log.IsDebugEnabled)
						{
							log.Debug("FullName: " + FullName);
						}
					}
				}
				if (IsAuthenticated)
				{
					var dalPerfilUsuario = dalManager.GetProvider<Sireass.Dal.IPerfilUsuarioDal>();
					using (var data = new Csla.Data.SafeDataReader(dalPerfilUsuario.Fetch(IdUsuario, true)))
					{
						Roles = new Csla.Core.MobileList<string>();
						while (data.Read())
						{							
							string rol = data.GetString("cPerfil");
							if (log.IsDebugEnabled)
							{
								log.Debug("rol: " + rol);
							}
							Roles.Add(rol);
						}
					}
				}
			}
		}

		private void DataPortal_Fetch(string username)
		{
			AuthenticationType = "Custom";
			IsAuthenticated = false;
			//var dal = new DataAccess.IdentityDal();
			//LoadUserData(username, dal);
			using (var dalManager = Sireass.Dal.DalFactory.GetManager())
			{
				var dal = dalManager.GetProvider<Sireass.Dal.IUsuarioDal>();
				using (var data = new Csla.Data.SafeDataReader(dal.Fetch(username)))
				{
					if (data.Read() && data.GetBoolean("bHabilitado"))
					{
						IsAuthenticated = true;
						Name = data.GetString("cUsuario");
						IdUsuario = data.GetInt64("nIdUsuario");
						IdPersona = data.GetInt64("nId_Persona");
						FullName = data.GetString("cNombre") + " " + data.GetString("cApellido_Paterno");
						string apellidoMaterno = data.GetString("cApellido_Materno").Trim();
						if (apellidoMaterno != null && apellidoMaterno.Length > 0)
						{
							FullName += " " + apellidoMaterno;
						}
					}
				}
				if (IsAuthenticated)
				{
					var dalPerfilUsuario = dalManager.GetProvider<Sireass.Dal.IPerfilUsuarioDal>();
					using (var data = new Csla.Data.SafeDataReader(dalPerfilUsuario.Fetch(IdUsuario, true)))
					{
						Roles = new Csla.Core.MobileList<string>();
						while (data.Read())
						{							
							string rol = data.GetString("cPerfil");
							if (log.IsDebugEnabled)
							{
								log.Debug("rol: " + rol);
							}
							Roles.Add(rol);
						}
					}
				}
			}
		}

		//private void LoadUserData(string username, DataAccess.IdentityDal dal)
		//{
		//    var userData = dal.GetUser(username);
		//    IsAuthenticated = (userData != null);
		//    if (IsAuthenticated)
		//    {
		//        Name = userData.Username;
		//        FullName = userData.FullName;
		//        Roles = new Csla.Core.MobileList<string>(dal.GetRoles(Name));
		//    }
		//}
	}
}
